#include "widget.h"
#include "ui_widget.h"
#include <QWidget>
#include <QMouseEvent>
#include <QGraphicsDropShadowEffect>
#include <QPropertyAnimation>
#include <QShortcut>
#include <QToolTip>
#include <QVector>
#include <QJsonObject>
#include "btform.h"
#include <QPixmap>
#include <QFile>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowFlag(Qt::WindowType::FramelessWindowHint); // 无边框窗口
    this->setAttribute(Qt::WA_TranslucentBackground); // 窗口背景透明

    InitUI();
    connectSignaleAndSlots();
}

void Widget::InitUI(){
    // 绘制阴影效果 -- 不生效
    QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect(this);
    shadowEffect->setOffset(0, 0); // 阴影偏移
    shadowEffect->setBlurRadius(20); // 阴影模糊半径
    shadowEffect->setColor(QColor(0, 0, 0, 80));  // 半透明黑色
    ui->background->setGraphicsEffect(shadowEffect);

    //  窗口从透明逐渐显示出来 的淡入动画
    QPropertyAnimation *animation = new QPropertyAnimation(this, "windowOpacity");
    animation->setDuration(500);
    animation->setStartValue(0.0);
    animation->setEndValue(1.0);
    animation->start();

    InitLovePlay();

    ui->rec->seticon(":/images/choice.png", "推荐", 1);
    ui->music->seticon(":/images/music.png", "播客", 2);
    ui->audio->seticon(":/images/radio.png", "漫游", 3);
    ui->like->seticon(":/images/mylove.png", "我喜欢", 4);
    ui->recent->seticon(":/images/recent.png", "最近播放", 5);
    ui->local->seticon(":/images/local.png", "本地", 6);

    ui->rec->showAnimal();
    ui->stackedWidget->setCurrentIndex(0);

    randomPiction();
    ui->recMusicBox->InitRecBoxUi(randomPiction(), 1);
    ui->supplyMusicBox->InitRecBoxUi(randomPiction(), 2);
}


void Widget::connectSignaleAndSlots(){
    // ⾃定义的btFrom按钮点击信号，当btForm点击后，设置对应的堆叠窗⼝
    connect(ui->rec, &BtForm::btClick, this, &Widget::onBtFormClick);
    connect(ui->music, &BtForm::btClick, this, &Widget::onBtFormClick);
    connect(ui->audio, &BtForm::btClick, this, &Widget::onBtFormClick);
    connect(ui->like, &BtForm::btClick, this, &Widget::onBtFormClick);
    connect(ui->local, &BtForm::btClick, this, &Widget::onBtFormClick);
    connect(ui->recent, &BtForm::btClick, this, &Widget::onBtFormClick);
}

// 推荐文本 + 推荐图片路径
QJsonArray Widget::randomPiction(){
    QVector<QString> vecImageName;
    vecImageName <<"001.png"<<"002.png"<<"003.png"<<"004.png"<<"005.png"<<"006.png"
                 <<"007.png"<<"008.png"<<"009.png"<<"010.png"<<"011.png"<<"012.png"
                 <<"013.png"<<"014.png"<<"015.png"<<"016.png"<<"017.png"<<"018.png"
                 <<"019.png"<<"020.png"<<"021.png"<<"022.png"<<"023.png"<<"024.png"
                 <<"025.png"<<"026.png"<<"027.png"<<"028.png"<<"029.png"<<"030.png"
                 <<"031.png"<<"032.png"<<"033.png"<<"034.png"<<"035.png"<<"036.png"
                 <<"037.png"<<"038.png"<<"039.png"<<"040.png";

    std::random_shuffle(vecImageName.begin(), vecImageName.end());

        // 001.png
        // path: ":/images/rec/"+vecImageName[i];
        // text: "推荐-001"
    QJsonArray objArray;
    for(int i = 0; i < vecImageName.size(); ++i)
    {
        QJsonObject obj;
        obj.insert("path", ":/images/rec/"+vecImageName[i]);
        // arg(i, 3, 10, QCchar('0'))
        // i：要放⼊%1位置的数据
        // 3: 三位数
        // 10：表⽰⼗进制数
        // QChar('0')：数字不够三位，前⾯⽤字符'0'填充
        QString strText = QString("推荐-%1").arg(i, 3, 10, QChar('0'));
        obj.insert("text", strText);
        objArray.append(obj);
    }
    return objArray;
}


void Widget::onBtFormClick(int id){
    // 1. 获取当前页面所有的 btForm 按钮类型对象
    QList<BtForm*> buttonList = this->findChildren<BtForm*>();

    // 2. 遍历所有对象, 如果不是当前 id 按钮, 则清除之前设置背景颜色
    foreach(BtForm* btitem, buttonList){
        if(id != btitem->getId()) btitem->clearBg();
        if(id == btitem->getId()) btitem->showAnimal();
    }
    // 3. 设置当前栈空间显示页面
    // 默认动画显示
    ui->stackedWidget->setCurrentIndex(id - 1);
}

void Widget::mousePressEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
        isDragging = true;
        // event->globalPos()：⿏标按下事件发⽣时，光标相对于屏幕左上⻆位置
        // frameGeometry().topLeft(): ⿏标按下事件发⽣时，窗⼝左上⻆位置
        // geometry(): 不包括边框及顶部标题区的范围
        // frameGeometry(): 包括边框及顶部标题区的范围
        // event->globalPos() - frameGeometry().topLeft() 即为：⿏标按下时，窗⼝左上⻆和光标之间的距离差
        // 想要窗⼝⿏标按下时窗⼝移动，只需要在mouseMoveEvent中，让光标和窗⼝左上⻆保持相同的位置差
        dragPosition = event->globalPos() - frameGeometry().topLeft(); // 鼠标按下时，窗⼝左上⻆和光标之间的距离差
        setCursor(Qt::ClosedHandCursor); // 可选：改变光标形状
    }
    QWidget::mousePressEvent(event);
}

void Widget::mouseMoveEvent(QMouseEvent *event) {
    if (isDragging && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - dragPosition);
    }
    QWidget::mouseMoveEvent(event);
}

void Widget::mouseReleaseEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
        isDragging = false;
        setCursor(Qt::ArrowCursor); // 恢复光标
    }
    QWidget::mouseReleaseEvent(event);
}

Widget::~Widget(){
    delete ui;
}



void Widget::on_quit_clicked(){
    close();
}

void Widget::InitLovePlay(){
    // 设置按钮为可切换状态
    ui->love->setCheckable(true);
    ui->love->setChecked(false);

    // 设置默认提示信息
    ui->love->setStatusTip("喜欢（Ctrl+L）");

    // 设置样式表（也可以写在 .qss 文件中）
    ui->love->setStyleSheet(
        "QPushButton {"
        "border: none;"
        "border-image: url(:/images/love1.png);"
        "border-position: center;"
        "border-repeat: no-repeat;"
        "width: 27px;"
        "height: 27px;"
        "}"
        "QPushButton:checked {"
        "border-image: url(:/images/love2.png);"
        "width: 27px;"
        "height: 27px;"
        "}"
        );
    // 创建快捷键 Ctrl+L
    QShortcut* shortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_L), this);
    connect(shortcut, &QShortcut::activated, this, &Widget::toggleLove);

}

void Widget::on_playLove_clicked(){
    // 喜欢
    bool isChecked = ui->love->isChecked();
    if (isChecked) {
        ui->love->setStatusTip("取消喜欢（Ctrl+L）");
        QToolTip::showText(QCursor::pos(), "取消喜欢（Ctrl+L）", ui->love);
    } else {
        ui->love->setStatusTip("喜欢（Ctrl+L）");
        QToolTip::showText(QCursor::pos(), "喜欢（Ctrl+L）", ui->love);
    }

}


void Widget::toggleLove(){
    ui->love->click(); // 触发按钮点击事件，自动调用 on_play_clicked
}




